package com.hqd.jjvm.rtda.memory;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.rtda.heap.JClass;
import com.hqd.jjvm.rtda.heap.JField;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 方法区
 */
public class JMethodArea {
    /**
     * 类信息
     */
    private static final Map<String, JClass> JCLASS_MAP = new HashMap<>();
    /**
     * 类文件信息
     */
    private static final Map<String, ClassFile> CLASS_FILE_MAP = new HashMap<>();
    /**
     * 静态变量
     */
    private static final Map<String, List<JField>> STATIC_JFIELD = new HashMap<>();

    public static void putStaticJField(JField jField) {
        String className = jField.getJClass().getClassName();
        synchronized (STATIC_JFIELD) {
            if (STATIC_JFIELD.get(className) == null) {
                List<JField> list = new LinkedList();
                list.add(jField);
                STATIC_JFIELD.put(className, list);
            } else {
                STATIC_JFIELD.get(className).add(jField);
            }
        }
    }

    public static ClassFile getClassFile(String className) {
        return CLASS_FILE_MAP.get(className);
    }

    public static void putAllClassFile(Map<String, ClassFile> classFileMap) {
        synchronized (CLASS_FILE_MAP) {
            CLASS_FILE_MAP.putAll(classFileMap);
        }
    }

    public static void putClassFile(String className, ClassFile classFile) {
        synchronized (CLASS_FILE_MAP) {
            CLASS_FILE_MAP.put(className, classFile);
        }
    }

    public static JClass getJClass(String className) {
        className = className.replaceAll("\\.", "/");
        return JCLASS_MAP.get(className);
    }

    public static void putJClass(JClass jClass) {
        synchronized (JCLASS_MAP) {
            JCLASS_MAP.put(jClass.getClassName(), jClass);
        }
    }
}
